<template>
  <div class="admin-page">
    <el-container>
      <el-main class="admin-main">
        <!-- 主内容区 -->
        <!-- 仪表盘 -->
        <div v-if="activeMenu === 'dashboard'" class="dashboard">
          <el-row :gutter="20">
            <el-col :span="6">
              <el-card class="stat-card">
                <div class="stat-content">
                  <div class="stat-icon users">
                    <el-icon :size="32"><User /></el-icon>
                  </div>
                  <div class="stat-info">
                    <h3>总用户数</h3>
                    <p class="stat-number">{{ userStats.total }}</p>
                  </div>
                </div>
              </el-card>
            </el-col>
            
            <el-col :span="6">
              <el-card class="stat-card">
                <div class="stat-content">
                  <div class="stat-icon photographers">
                    <el-icon :size="32"><Camera /></el-icon>
                  </div>
                  <div class="stat-info">
                    <h3>摄影师数</h3>
                    <p class="stat-number">{{ userStats.photographers }}</p>
                  </div>
                </div>
              </el-card>
            </el-col>
            
            <el-col :span="6">
              <el-card class="stat-card">
                <div class="stat-content">
                  <div class="stat-icon orders">
                    <el-icon :size="32"><Document /></el-icon>
                  </div>
                  <div class="stat-info">
                    <h3>订单总数</h3>
                    <p class="stat-number">{{ orderStats.total }}</p>
                  </div>
                </div>
              </el-card>
            </el-col>
            
            <el-col :span="6">
              <el-card class="stat-card">
                <div class="stat-content">
                  <div class="stat-icon revenue">
                    <el-icon :size="32"><Money /></el-icon>
                  </div>
                  <div class="stat-info">
                    <h3>完成订单数</h3>
                    <p class="stat-number">{{ orderStats.completed }}</p>
                  </div>
                </div>
              </el-card>
            </el-col>
          </el-row>
          
          <el-row :gutter="20" style="margin-top: 20px;">
            <el-col :span="12">
              <el-card>
                <template #header>
                  <span>最近订单</span>
                </template>
                <el-table :data="recentOrders" style="width: 100%">
                  <el-table-column prop="id" label="订单号" width="100" />
                  <el-table-column prop="user" label="用户" />
                  <el-table-column prop="photographer" label="摄影师" />
                  <el-table-column prop="status" label="状态">
                    <template #default="{ row }: { row: any }">
                      <el-tag :type="getStatusType(row.status)">
                        {{ row.status }}
                      </el-tag>
                    </template>
                  </el-table-column>
                </el-table>
              </el-card>
            </el-col>
            
            <el-col :span="12">
              <el-card>
                <template #header>
                  <span>系统公告</span>
                </template>
                <div class="announcements">
                  <div v-for="notice in announcements" :key="notice.id" class="announcement-item">
                    <h4>{{ notice.title }}</h4>
                    <p>{{ notice.content }}</p>
                    <span class="notice-time">{{ notice.time }}</span>
                  </div>
                </div>
              </el-card>
            </el-col>
          </el-row>
        </div>
        
        <!-- 用户管理 -->
        <div v-else-if="activeMenu === 'users'" class="users-management">
          <el-card>
            <template #header>
              <div class="card-header">
                <span>用户管理</span>
                <div class="header-actions">
                  <el-input
                    v-model="searchKeyword"
                    placeholder="搜索用户名或真实姓名"
                    style="width: 300px; margin-right: 10px;"
                    clearable
                    @input="handleSearch"
                  >
                    <template #prefix>
                      <el-icon><Search /></el-icon>
                    </template>
                  </el-input>
                  <el-button type="primary" @click="refreshUsers">
                    <el-icon><Refresh /></el-icon>
                    刷新
                  </el-button>
                </div>
              </div>
            </template>
            
            <el-table
              :data="filteredUsers"
              style="width: 100%"
              v-loading="loading"
              @selection-change="handleSelectionChange"
            >
              <el-table-column type="selection" width="55" />
              <el-table-column prop="id" label="ID" width="80" />
              <el-table-column prop="username" label="用户名" width="120" />
              <el-table-column prop="realName" label="真实姓名" width="120" />
              <el-table-column prop="phone" label="手机号" width="130" />
              <el-table-column prop="gender" label="性别" width="80">
                <template #default="scope">
                  <el-tag :type="getGenderType(scope.row.gender)">
                    {{ getGenderText(scope.row.gender) }}
                  </el-tag>
                </template>
              </el-table-column>
              <el-table-column prop="birthday" label="生日" width="120">
                <template #default="scope">
                  {{ formatDate(scope.row.birthday) }}
                </template>
              </el-table-column>
              <el-table-column prop="status" label="状态" width="100">
                <template #default="scope">
                  <el-switch
                    :model-value="scope.row.status"
                    :active-value="1"
                    :inactive-value="0"
                    @change="(val: number) => handleStatusChange(scope.row, val)"
                  />
                </template>
              </el-table-column>
              <el-table-column prop="role" label="角色" width="100">
                <template #default="scope">
                  <el-tag :type="scope.row.role === 1 ? 'danger' : 'info'">
                    {{ scope.row.role === 1 ? '管理员' : '普通用户' }}
                  </el-tag>
                </template>
              </el-table-column>
              <el-table-column prop="registerTime" label="注册时间" width="160">
                <template #default="scope">
                  {{ formatDateTime(scope.row.registerTime) }}
                </template>
              </el-table-column>
              <el-table-column label="操作" width="200" fixed="right">
                <template #default="scope">
                  <el-button
                    size="small"
                    type="primary"
                    @click="handleEdit(scope.row)"
                  >
                    编辑
                  </el-button>
                  <el-button
                    size="small"
                    type="danger"
                    @click="handleDelete(scope.row)"
                  >
                    删除
                  </el-button>
                </template>
              </el-table-column>
            </el-table>
            
            <div class="table-footer">
              <el-button
                type="danger"
                :disabled="selectedUsers.length === 0"
                @click="handleBatchDelete"
              >
                批量删除 ({{ selectedUsers.length }})
              </el-button>
            </div>
          </el-card>
        </div>
        
        <!-- 摄影师管理 -->
        <div v-else-if="activeMenu === 'photographers'" class="photographers-management">
          <el-card>
            <template #header>
              <div class="card-header">
                <span>摄影师管理</span>
                <div class="header-actions">
                  <el-input
                    v-model="photographerSearch"
                    placeholder="搜索姓名或手机号"
                    style="width: 300px; margin-right: 10px;"
                    clearable
                    @input="handlePhotographerSearch"
                  >
                    <template #prefix>
                      <el-icon><Search /></el-icon>
                    </template>
                  </el-input>
                  <el-button type="primary" @click="fetchPhotographers">
                    <el-icon><Refresh /></el-icon>
                    刷新
                  </el-button>
                </div>
              </div>
            </template>
            <el-table
              :data="filteredPhotographers"
              style="width: 100%"
              v-loading="photographerLoading"
              @selection-change="handlePhotographerSelectionChange"
            >
              <el-table-column type="selection" width="55" />
              <el-table-column prop="id" label="ID" width="80" />
              <el-table-column prop="name" label="姓名" width="120" />
              <el-table-column prop="phone" label="电话" width="130" />
              <el-table-column prop="style" label="擅长风格" width="120" />
              <el-table-column prop="intro" label="简介" width="150" />
              <el-table-column prop="workYears" label="工作年限" width="100" />
              <el-table-column prop="avatar" label="头像" width="80">
                <template #default="scope">
                  <el-avatar :src="scope.row.avatar" />
                </template>
              </el-table-column>
              <el-table-column prop="authStatus" label="认证状态" width="100">
                <template #default="scope">
                  <el-tag :type="getAuthStatusType(scope.row.authStatus)">
                    {{ getAuthStatusText(scope.row.authStatus) }}
                  </el-tag>
                </template>
              </el-table-column>
              <el-table-column prop="availableSchedule" label="可用档期" width="120" />
              <el-table-column prop="createTime" label="创建时间" width="160">
                <template #default="scope">
                  {{ formatDateTime(scope.row.createTime) }}
                </template>
              </el-table-column>
              <el-table-column prop="updateTime" label="更新时间" width="160">
                <template #default="scope">
                  {{ formatDateTime(scope.row.updateTime) }}
                </template>
              </el-table-column>
              <el-table-column label="操作" width="200" fixed="right">
                <template #default="scope">
                  <el-button size="small" type="primary" @click="handlePhotographerEdit(scope.row)">编辑</el-button>
                  <el-button size="small" type="danger" @click="handlePhotographerDelete(scope.row)">删除</el-button>
                </template>
              </el-table-column>
            </el-table>
            <div class="table-footer">
              <el-button
                type="danger"
                :disabled="selectedPhotographers.length === 0"
                @click="handlePhotographerBatchDelete"
              >
                批量删除 ({{ selectedPhotographers.length }})
              </el-button>
            </div>
          </el-card>
          <!-- 编辑摄影师对话框 -->
          <el-dialog
            v-model="editPhotographerDialog"
            title="编辑摄影师"
            width="600px"
          >
            <el-form :model="editPhotographerForm" label-width="100px">
              <el-form-item label="姓名">
                <el-input v-model="editPhotographerForm.name" />
              </el-form-item>
              <el-form-item label="电话">
                <el-input v-model="editPhotographerForm.phone" />
              </el-form-item>
              <el-form-item label="擅长风格">
                <el-input v-model="editPhotographerForm.style" />
              </el-form-item>
              <el-form-item label="简介">
                <el-input v-model="editPhotographerForm.intro" type="textarea" />
              </el-form-item>
              <el-form-item label="工作年限">
                <el-input-number v-model="editPhotographerForm.workYears" :min="0" />
              </el-form-item>
              <el-form-item label="头像">
                <el-input v-model="editPhotographerForm.avatar" placeholder="头像链接" />
              </el-form-item>
              <el-form-item label="认证状态">
                <el-select v-model="editPhotographerForm.authStatus" placeholder="请选择认证状态">
                  <el-option label="未认证" :value="0" />
                  <el-option label="已认证" :value="1" />
                  <el-option label="认证失败" :value="2" />
                </el-select>
              </el-form-item>
              <el-form-item label="可用档期">
                <el-input v-model="editPhotographerForm.availableSchedule" />
              </el-form-item>
            </el-form>
            <template #footer>
              <span class="dialog-footer">
                <el-button @click="editPhotographerDialog = false">取消</el-button>
                <el-button type="primary" @click="handleSavePhotographerEdit" :loading="savePhotographerLoading">
                  保存
                </el-button>
              </span>
            </template>
          </el-dialog>
        </div>
        
        <!-- 摄影师申请审核 -->
        <div v-else-if="activeMenu === 'applications'" class="applications">
          <el-card style="margin-top: 30px;">
            <template #header>
              <span>摄影师申请审核</span>
            </template>
            <el-table :data="applicationList" style="width: 100%">
              <el-table-column prop="id" label="申请ID" width="80" />
              <el-table-column prop="realName" label="姓名" />
              <el-table-column prop="phone" label="电话" />
              <el-table-column prop="intro" label="简介" />
              <el-table-column prop="status" label="状态" />
              <el-table-column prop="remark" label="备注" />
              <el-table-column label="操作" width="180">
                <template #default="{ row }">
                  <el-button v-if="row.status === 'PENDING'" type="success" size="small" @click="review(row.id, 'APPROVED')">通过</el-button>
                  <el-button v-if="row.status === 'PENDING'" type="danger" size="small" @click="review(row.id, 'REJECTED')">拒绝</el-button>
                </template>
              </el-table-column>
            </el-table>
          </el-card>
        </div>
        
        <!-- 订单管理 -->
        <div v-else-if="activeMenu === 'orders'" class="orders-management">
          <el-card>
            <template #header>
              <div class="card-header">
                <span>订单管理</span>
                <div class="header-actions">
                  <el-select v-model="orderStatusFilter" placeholder="订单状态" clearable style="width: 150px; margin-right: 10px;">
                    <el-option label="待支付" value="PENDING" />
                    <el-option label="已确认" value="CONFIRMED" />
                    <el-option label="拍摄中" value="IN_PROGRESS" />
                    <el-option label="已完成" value="COMPLETED" />
                    <el-option label="已取消" value="CANCELED" />
                  </el-select>
                  <el-button type="primary" @click="fetchOrders">
                    <el-icon><Refresh /></el-icon>
                    刷新
                  </el-button>
                </div>
              </div>
            </template>
            
            <el-table :data="filteredOrders" style="width: 100%" v-loading="orderLoading">
              <el-table-column prop="id" label="订单号" width="100" />
              <el-table-column prop="userName" label="用户" width="120" />
              <el-table-column prop="photographerName" label="摄影师" width="120" />
              <el-table-column prop="packageName" label="套餐" width="120" />
              <el-table-column prop="totalPrice" label="金额" width="100">
                <template #default="scope">
                  ¥{{ scope.row.totalPrice }}
                </template>
              </el-table-column>
              <el-table-column prop="shootingTime" label="拍摄时间" width="160">
                <template #default="scope">
                  {{ formatDateTime(scope.row.shootingTime) }}
                </template>
              </el-table-column>
              <el-table-column prop="status" label="状态" width="100">
                <template #default="scope">
                  <el-tag :type="getStatusType(scope.row.status)">
                    {{ getOrderStatusText(scope.row.status) }}
                  </el-tag>
                </template>
              </el-table-column>
              <el-table-column prop="createTime" label="创建时间" width="160">
                <template #default="scope">
                  {{ formatDateTime(scope.row.createTime) }}
                </template>
              </el-table-column>
              <el-table-column label="操作" width="150" fixed="right">
                <template #default="scope">
                  <el-button size="small" type="primary" @click="viewOrderDetail(scope.row.id)">
                    查看详情
                  </el-button>
                  <el-button 
                    v-if="scope.row.status === 'IN_PROGRESS'" 
                    size="small" 
                    type="success" 
                    @click="completeOrder(scope.row.id)"
                  >
                    完成订单
                  </el-button>
                </template>
              </el-table-column>
            </el-table>
          </el-card>
        </div>
        
        <!-- 其他页面内容 -->
        <div class="page-content">
          <el-empty description="功能开发中..." />
        </div>
        <div>{{ applicationList }}</div>
      </el-main>
      <el-aside width="250px" class="admin-sidebar">
        <div class="sidebar-header">
          <el-icon :size="24"><Setting /></el-icon>
          <h3>管理后台</h3>
        </div>
        
        <el-menu
          :default-active="activeMenu"
          class="sidebar-menu"
          @select="handleMenuSelect"
        >
          <el-menu-item index="dashboard">
            <el-icon><DataBoard /></el-icon>
            <span>仪表盘</span>
          </el-menu-item>
          
          <el-menu-item index="users">
            <el-icon><User /></el-icon>
            <span>用户管理</span>
          </el-menu-item>
          
          <el-menu-item index="photographers">
            <el-icon><Camera /></el-icon>
            <span>摄影师管理</span>
          </el-menu-item>
          
          <el-menu-item index="orders">
            <el-icon><Document /></el-icon>
            <span>订单管理</span>
          </el-menu-item>
          
          <el-menu-item index="applications">
            <el-icon><Document /></el-icon>
            <span>申请审核</span>
          </el-menu-item>
          
          <el-menu-item index="statistics">
            <el-icon><TrendCharts /></el-icon>
            <span>数据统计</span>
          </el-menu-item>
        </el-menu>
        
        <div class="sidebar-footer">
          <el-button 
            type="danger" 
            @click="handleLogout"
            class="logout-btn"
          >
            <el-icon><SwitchButton /></el-icon>
            退出登录
          </el-button>
        </div>
      </el-aside>
    </el-container>
    
    <!-- 编辑用户对话框 -->
    <el-dialog
      v-model="editDialogVisible"
      title="编辑用户信息"
      width="600px"
      @close="resetEditForm"
    >
      <el-form
        ref="editFormRef"
        :model="editForm"
        :rules="editRules"
        label-width="100px"
      >
        <el-form-item label="用户名" prop="username">
          <el-input v-model="editForm.username" disabled />
        </el-form-item>
        <el-form-item label="真实姓名" prop="realName">
          <el-input v-model="editForm.realName" />
        </el-form-item>
        <el-form-item label="手机号" prop="phone">
          <el-input v-model="editForm.phone" />
        </el-form-item>
        <el-form-item label="性别" prop="gender">
          <el-select v-model="editForm.gender" placeholder="请选择性别" style="width: 100%">
            <el-option label="女" :value="0" />
            <el-option label="男" :value="1" />
            <el-option label="其他" :value="2" />
          </el-select>
        </el-form-item>
        <el-form-item label="生日" prop="birthday">
          <el-date-picker
            v-model="editForm.birthday"
            type="date"
            placeholder="请选择生日"
            style="width: 100%"
            format="YYYY-MM-DD"
            value-format="YYYY-MM-DD"
          />
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-switch
            v-model="editForm.status"
            :active-value="1"
            :inactive-value="0"
            active-text="正常"
            inactive-text="禁用"
          />
        </el-form-item>
        <el-form-item label="角色" prop="role">
          <el-select v-model="editForm.role" placeholder="请选择角色" style="width: 100%">
            <el-option label="普通用户" :value="0" />
            <el-option label="管理员" :value="1" />
          </el-select>
        </el-form-item>
      </el-form>
      
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="editDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="handleSaveEdit" :loading="saveLoading">
            保存
          </el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted, computed } from 'vue'
import { useRouter } from 'vue-router'
import { useUserStore } from '../stores/user'
import { ElMessage, ElMessageBox } from 'element-plus'
import type { FormInstance, FormRules } from 'element-plus'
import api from '../utils/api'

const router = useRouter()
const userStore = useUserStore()
const activeMenu = ref('dashboard')
const loading = ref(false)
const saveLoading = ref(false)
const editDialogVisible = ref(false)
const editFormRef = ref<FormInstance>()

// 用户数据
const users = ref<any[]>([])
const filteredUsers = ref<any[]>([])
const selectedUsers = ref<any[]>([])
const searchKeyword = ref('')

// 用户统计
const userStats = ref({
  total: 0,
  photographers: 0
})

// 订单统计
const orderStats = ref({
  total: 0,
  completed: 0
})

// 订单管理相关变量
const orders = ref<any[]>([])
const filteredOrders = ref<any[]>([])
const orderLoading = ref(false)
const orderStatusFilter = ref('')

// 编辑表单
const editForm = reactive({
  id: null as number | null,
  username: '',
  realName: '',
  phone: '',
  gender: undefined as number | undefined,
  birthday: '',
  status: 1,
  role: 0
})

// 编辑表单验证规则
const editRules: FormRules = {
  realName: [
    { required: true, message: '请输入真实姓名', trigger: 'blur' },
    { min: 2, max: 10, message: '姓名长度在2到10个字符', trigger: 'blur' }
  ],
  phone: [
    { required: true, message: '请输入手机号码', trigger: 'blur' },
    { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号码', trigger: 'blur' }
  ],
  gender: [
    { required: true, message: '请选择性别', trigger: 'change' }
  ],
  birthday: [
    { required: true, message: '请选择生日', trigger: 'change' }
  ]
}

// 获取最近订单
const fetchRecentOrders = async () => {
  try {
    const res = await api.get('/orders/recent', { params: { limit: 5 } })
    recentOrders.value = (res.data.data || []).map(order => ({
      id: order.id,
      user: order.userName || order.user || '-',
      photographer: order.photographerName || order.photographer || '-',
      status: order.status
    }))
  } catch (e) {
    recentOrders.value = []
  }
}

// 获取公告
const fetchAnnouncements = async () => {
  try {
    const res = await api.get('/announcement/list')
    announcements.value = res.data.data || []
  } catch (e) {
    announcements.value = []
  }
}

// 获取用户列表
const fetchUsers = async () => {
  try {
    loading.value = true
    const response = await api.get('/photo/user/list')
    users.value = response.data.data || []
    filteredUsers.value = [...users.value]
    
    // 更新统计数据
    userStats.value.total = users.value.length
    userStats.value.photographers = users.value.filter(user => user.role === 2).length
  } catch (error) {
    console.error('获取用户列表失败:', error)
    ElMessage.error('获取用户列表失败')
  } finally {
    loading.value = false
  }
}

// 获取订单统计
const fetchOrderStats = async () => {
  try {
    // 获取所有订单
    const response = await api.get('/orders/list')
    const orders = response.data.data || []
    
    orderStats.value.total = orders.length
    orderStats.value.completed = orders.filter((order: any) => order.status === 'COMPLETED').length
  } catch (error) {
    console.error('获取订单统计失败:', error)
    // 不显示错误消息，因为可能没有订单管理接口
  }
}

// 获取订单列表
const fetchOrders = async () => {
  try {
    orderLoading.value = true
    const response = await api.get('/orders/list')
    orders.value = response.data.data || []
    filteredOrders.value = [...orders.value]
  } catch (error) {
    console.error('获取订单列表失败:', error)
    ElMessage.error('获取订单列表失败')
  } finally {
    orderLoading.value = false
  }
}

// 获取订单状态文本
const getOrderStatusText = (status: string) => {
  const statusMap: Record<string, string> = {
    'PENDING': '待支付',
    'CONFIRMED': '已确认',
    'IN_PROGRESS': '拍摄中',
    'COMPLETED': '已完成',
    'CANCELED': '已取消',
    'FAILED': '已失败'
  }
  return statusMap[status] || '未知状态'
}

// 查看订单详情
const viewOrderDetail = (orderId: number) => {
  router.push(`/order/${orderId}`)
}

// 完成订单
const completeOrder = async (orderId: number) => {
  try {
    await ElMessageBox.confirm('确定要完成这个订单吗？', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })
    
    await api.put(`/orders/${orderId}/complete`, {})
    ElMessage.success('订单已完成')
    fetchOrders() // 刷新订单列表
    fetchOrderStats() // 刷新统计数据
  } catch (error) {
    if (error !== 'cancel') {
      console.error('完成订单失败:', error)
      ElMessage.error('完成订单失败，请重试')
    }
  }
}

// 搜索用户
const handleSearch = () => {
  if (!searchKeyword.value) {
    filteredUsers.value = [...users.value]
  } else {
    filteredUsers.value = users.value.filter(user => 
      user.username?.includes(searchKeyword.value) ||
      user.realName?.includes(searchKeyword.value)
    )
  }
}

// 刷新用户列表
const refreshUsers = () => {
  fetchUsers()
}

// 处理表格选择
const handleSelectionChange = (selection: any[]) => {
  selectedUsers.value = selection
}

// 处理状态变更
const handleStatusChange = async (user: any, newVal: number) => {
  try {
    await api.post('/photo/user/update', [
      {
        id: user.id,
        status: newVal
      }
    ])
    ElMessage.success('状态更新成功')
  } catch (error) {
    console.error('状态更新失败:', error)
    ElMessage.error('状态更新失败')
    // 恢复原状态
    user.status = user.status === 1 ? 0 : 1
  }
}

// 编辑用户
const handleEdit = (user: any) => {
  Object.assign(editForm, {
    id: user.id,
    username: user.username,
    realName: user.realName,
    phone: user.phone,
    gender: user.gender,
    birthday: user.birthday ? formatDate(user.birthday) : '',
    status: user.status,
    role: user.role
  })
  editDialogVisible.value = true
}

// 保存编辑
const handleSaveEdit = async () => {
  if (!editFormRef.value) return
  
  try {
    await editFormRef.value.validate()
    saveLoading.value = true
    
    const updateData = {
      id: editForm.id,
      realName: editForm.realName,
      phone: editForm.phone,
      gender: editForm.gender,
      birthday: editForm.birthday ? new Date(editForm.birthday) : null,
      status: editForm.status,
      role: editForm.role
    }
    
    await api.post('/photo/user/update', [updateData])
    ElMessage.success('用户信息更新成功')
    editDialogVisible.value = false
    fetchUsers()
  } catch (error) {
    console.error('更新用户信息失败:', error)
    ElMessage.error('更新用户信息失败')
  } finally {
    saveLoading.value = false
  }
}

// 删除用户
const handleDelete = async (user: any) => {
  try {
    await ElMessageBox.confirm(
      `确定要删除用户 "${user.username}" 吗？此操作不可恢复。`,
      '确认删除',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )
    
    // 调用后端删除API
    await api.post('/photo/user/delete', [user])
    ElMessage.success('用户删除成功')
    fetchUsers() // 刷新用户列表
  } catch (error: any) {
    if (error !== 'cancel') {
      console.error('删除用户失败:', error)
      ElMessage.error(error.response?.data?.msg || '删除用户失败')
    }
  }
}

// 批量删除
const handleBatchDelete = async () => {
  if (selectedUsers.value.length === 0) return
  
  try {
    await ElMessageBox.confirm(
      `确定要删除选中的 ${selectedUsers.value.length} 个用户吗？此操作不可恢复。`,
      '确认批量删除',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )
    
    // 调用后端批量删除API
    await api.post('/photo/user/delete', selectedUsers.value)
    ElMessage.success('批量删除成功')
    selectedUsers.value = [] // 清空选择
    fetchUsers() // 刷新用户列表
  } catch (error: any) {
    if (error !== 'cancel') {
      console.error('批量删除失败:', error)
      ElMessage.error(error.response?.data?.msg || '批量删除失败')
    }
  }
}

// 重置编辑表单
const resetEditForm = () => {
  Object.assign(editForm, {
    id: null,
    username: '',
    realName: '',
    phone: '',
    gender: undefined,
    birthday: '',
    status: 1,
    role: 0
  })
  editFormRef.value?.clearValidate()
}

// 格式化日期
const formatDate = (date: string | Date) => {
  if (!date) return ''
  const d = new Date(date)
  return d.toLocaleDateString()
}

// 格式化日期时间
const formatDateTime = (dateTime: string | Date) => {
  if (!dateTime) return ''
  const d = new Date(dateTime)
  return d.toLocaleString()
}

// 获取性别文本
const getGenderText = (gender: number) => {
  const genderMap: Record<number, string> = {
    0: '女',
    1: '男',
    2: '其他'
  }
  return genderMap[gender] || '未知'
}

// 获取性别标签类型
const getGenderType = (gender: number) => {
  const typeMap: Record<number, string> = {
    0: 'danger',
    1: 'primary',
    2: 'info'
  }
  return typeMap[gender] || 'info'
}

// 获取订单状态标签类型
const getStatusType = (status: string) => {
  const statusMap: Record<string, string> = {
    'PENDING': 'warning',
    'CONFIRMED': 'primary',
    'IN_PROGRESS': 'success',
    'COMPLETED': 'success',
    'CANCELED': 'info',
    'FAILED': 'danger'
  }
  return statusMap[status] || 'info'
}

const handleMenuSelect = (index: string) => {
  activeMenu.value = index
  if (index === 'users') {
    fetchUsers()
  } else if (index === 'photographers') {
    fetchPhotographers()
  } else if (index === 'orders') {
    fetchOrders()
  } else if (index === 'applications') {
    fetchApplications()
  }
}

const getMenuTitle = () => {
  const titles: Record<string, string> = {
    dashboard: '仪表盘',
    users: '用户管理',
    photographers: '摄影师管理',
    orders: '订单管理',
    applications: '申请审核',
    statistics: '数据统计'
  }
  return titles[activeMenu.value] || '管理后台'
}

const getAuthStatusText = (status: number): string => {
  switch (status) {
    case 0: return '未认证'
    case 1: return '已认证'
    case 2: return '认证失败'
    default: return '未知'
  }
}

const getAuthStatusType = (status: number): string => {
  switch (status) {
    case 0: return 'info'
    case 1: return 'success'
    case 2: return 'danger'
    default: return 'info'
  }
}

const handleUserCommand = (command: string) => {
  if (command === 'logout') {
    handleLogout()
  } else if (command === 'profile') {
    ElMessage.info('个人资料功能开发中...')
  }
}

const handleLogout = async () => {
  try {
    await ElMessageBox.confirm('确定要退出登录吗？', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })
    
    userStore.logout()
    ElMessage.success('已退出登录')
    router.push({ name: 'login' })
  } catch {
    // 用户取消
  }
}

const photographers = ref<any[]>([])
const filteredPhotographers = ref<any[]>([])
const selectedPhotographers = ref<any[]>([])
const photographerSearch = ref('')
const photographerLoading = ref(false)
const editPhotographerDialog = ref(false)
const editPhotographerForm = ref<any>({})
const savePhotographerLoading = ref(false)
let isPhotographerTableMounted = false;

const fetchPhotographers = async () => {
  photographerLoading.value = true
  const res = await api.get('/photo/photographer/list')
  photographers.value = res.data.data || []
  filteredPhotographers.value = [...photographers.value]
  photographerLoading.value = false
  isPhotographerTableMounted = true // 数据加载完毕
}

const handlePhotographerSearch = () => {
  if (!photographerSearch.value) {
    filteredPhotographers.value = [...photographers.value]
  } else {
    filteredPhotographers.value = photographers.value.filter(p =>
      p.name?.includes(photographerSearch.value) ||
      p.phone?.includes(photographerSearch.value)
    )
  }
}

const handlePhotographerSelectionChange = (selection: any[]) => {
  selectedPhotographers.value = selection
}

const handlePhotographerStatusChange = (row: any, newVal: any) => {
  if (!isPhotographerTableMounted) return; // 首次渲染不触发
  if (row.status !== newVal) {
    row.status = newVal
    api.post('/photo/photographer/update', editPhotographerForm.value)
    ElMessage.success('状态更新成功')
  }
}

const handlePhotographerEdit = (photographer: any) => {
  editPhotographerForm.value = { ...photographer }
  editPhotographerDialog.value = true
}

const handlePhotographerDelete = async (photographer: any) => {
  await ElMessageBox.confirm(
    `确定要删除摄影师 "${photographer.name}" 吗？此操作不可恢复。`,
    '确认删除',
    { confirmButtonText: '确定', cancelButtonText: '取消', type: 'warning' }
  )
  await api.post('/photo/photographer/deleteBatch', [photographer.id])
  ElMessage.success('删除成功')
  fetchPhotographers()
}

const handlePhotographerBatchDelete = async () => {
  if (selectedPhotographers.value.length === 0) return
  await ElMessageBox.confirm(
    `确定要删除选中的 ${selectedPhotographers.value.length} 个摄影师吗？此操作不可恢复。`,
    '确认批量删除',
    { confirmButtonText: '确定', cancelButtonText: '取消', type: 'warning' }
  )
  // 只传id数组
  const ids = selectedPhotographers.value.map(p => p.id)
  await api.post('/photo/photographer/deleteBatch', ids)
  ElMessage.success('批量删除成功')
  selectedPhotographers.value = []
  fetchPhotographers()
}

const handleSavePhotographerEdit = async () => {
  savePhotographerLoading.value = true
  await api.post('/photo/photographer/update', editPhotographerForm.value)
  ElMessage.success('保存成功')
  editPhotographerDialog.value = false
  fetchPhotographers()
  savePhotographerLoading.value = false
}

const applicationList = ref<any[]>([])

const fetchApplications = async () => {
  const res = await api.get('/application/list')
  console.log('申请列表', res.data.data)
  applicationList.value = res.data.data || []
}

const review = async (id: number, status: string) => {
  await api.put(`/application/${id}/review`, null, { params: { status } })
  ElMessage.success('操作成功')
  fetchApplications()
}

const recentOrders = ref<any[]>([])
const announcements = ref<any[]>([])

onMounted(() => {
  // 检查用户权限
  if (!userStore.isLoggedIn || userStore.user?.role !== 1) {
    ElMessage.error('无权限访问管理后台')
    router.push('/')
  }
  fetchApplications()
  fetchUsers()
  fetchOrderStats()
  fetchRecentOrders()
  fetchAnnouncements()
})
</script>

<style>
.admin-page,
.el-container {
  width: 100vw;
  height: 100vh;
  margin: 0;
  padding: 0;
  box-sizing: border-box;
}

.el-main {
  width: 100%;
  min-width: 0;
  margin: 0;
  padding: 20px;
  box-sizing: border-box;
  background: #f0f2f5;
  /* 让内容区铺满 */
  display: flex;
  flex-direction: column;
}

.admin-sidebar {
  background: #304156;
  color: white;
  display: flex;
  flex-direction: column;
}

.sidebar-header {
  padding: 20px;
  display: flex;
  align-items: center;
  gap: 10px;
  border-bottom: 1px solid #435266;
}

.sidebar-header h3 {
  margin: 0;
  color: white;
}

.sidebar-menu {
  flex: 1;
  border: none;
  background: transparent;
}

.sidebar-menu :deep(.el-menu-item) {
  color: #bfcbd9;
  border: none;
}

.sidebar-menu :deep(.el-menu-item:hover) {
  background: #263445;
  color: white;
}

.sidebar-menu :deep(.el-menu-item.is-active) {
  background: #409eff;
  color: white;
}

.sidebar-footer {
  padding: 20px;
  border-top: 1px solid #435266;
}

.logout-btn {
  width: 100%;
}

.admin-header {
  background: white;
  border-bottom: 1px solid #e4e7ed;
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 0 20px;
}

.header-left h2 {
  margin: 0;
  color: #303133;
}

.user-info {
  display: flex;
  align-items: center;
  gap: 8px;
  cursor: pointer;
  padding: 8px 12px;
  border-radius: 6px;
  transition: background 0.3s;
}

.user-info:hover {
  background: #f5f7fa;
}

.username {
  color: #606266;
  font-weight: 500;
}

.admin-main {
  background: #f0f2f5;
  padding: 20px;
}

.stat-card {
  margin-bottom: 20px;
}

.stat-content {
  display: flex;
  align-items: center;
  gap: 20px;
}

.stat-icon {
  width: 60px;
  height: 60px;
  border-radius: 12px;
  display: flex;
  align-items: center;
  justify-content: center;
  color: white;
}

.stat-icon.users {
  background: linear-gradient(135deg, #667eea, #764ba2);
}

.stat-icon.photographers {
  background: linear-gradient(135deg, #f093fb, #f5576c);
}

.stat-icon.orders {
  background: linear-gradient(135deg, #4facfe, #00f2fe);
}

.stat-icon.revenue {
  background: linear-gradient(135deg, #43e97b, #38f9d7);
}

.stat-info h3 {
  margin: 0 0 8px 0;
  color: #606266;
  font-size: 14px;
  font-weight: normal;
}

.stat-number {
  margin: 0;
  color: #303133;
  font-size: 24px;
  font-weight: bold;
}

.announcements {
  max-height: 300px;
  overflow-y: auto;
}

.announcement-item {
  padding: 15px 0;
  border-bottom: 1px solid #f0f0f0;
}

.announcement-item:last-child {
  border-bottom: none;
}

.announcement-item h4 {
  margin: 0 0 8px 0;
  color: #303133;
  font-size: 16px;
}

.announcement-item p {
  margin: 0 0 8px 0;
  color: #606266;
  font-size: 14px;
  line-height: 1.5;
}

.notice-time {
  color: #909399;
  font-size: 12px;
}

/* 用户管理样式 */
.users-management {
  min-height: calc(100vh - 200px);
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.header-actions {
  display: flex;
  align-items: center;
}

.table-footer {
  margin-top: 20px;
  padding-top: 20px;
  border-top: 1px solid #f0f0f0;
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 10px;
}
</style>

<style scoped>
.admin-page,
.el-container {
  width: 100vw;
  height: 100vh;
  margin: 0;
  padding: 0;
  box-sizing: border-box;
}

.el-main {
  width: 100%;
  min-width: 0;
  margin: 0;
  padding: 20px;
  box-sizing: border-box;
  background: #f0f2f5;
  /* 让内容区铺满 */
  display: flex;
  flex-direction: column;
}

.admin-sidebar {
  background: #304156;
  color: white;
  display: flex;
  flex-direction: column;
}

.sidebar-header {
  padding: 20px;
  display: flex;
  align-items: center;
  gap: 10px;
  border-bottom: 1px solid #435266;
}

.sidebar-header h3 {
  margin: 0;
  color: white;
}

.sidebar-menu {
  flex: 1;
  border: none;
  background: transparent;
}

.sidebar-menu :deep(.el-menu-item) {
  color: #bfcbd9;
  border: none;
}

.sidebar-menu :deep(.el-menu-item:hover) {
  background: #263445;
  color: white;
}

.sidebar-menu :deep(.el-menu-item.is-active) {
  background: #409eff;
  color: white;
}

.sidebar-footer {
  padding: 20px;
  border-top: 1px solid #435266;
}

.logout-btn {
  width: 100%;
}

.admin-header {
  background: white;
  border-bottom: 1px solid #e4e7ed;
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 0 20px;
}

.header-left h2 {
  margin: 0;
  color: #303133;
}

.user-info {
  display: flex;
  align-items: center;
  gap: 8px;
  cursor: pointer;
  padding: 8px 12px;
  border-radius: 6px;
  transition: background 0.3s;
}

.user-info:hover {
  background: #f5f7fa;
}

.username {
  color: #606266;
  font-weight: 500;
}

.admin-main {
  background: #f0f2f5;
  padding: 20px;
}

.stat-card {
  margin-bottom: 20px;
}

.stat-content {
  display: flex;
  align-items: center;
  gap: 20px;
}

.stat-icon {
  width: 60px;
  height: 60px;
  border-radius: 12px;
  display: flex;
  align-items: center;
  justify-content: center;
  color: white;
}

.stat-icon.users {
  background: linear-gradient(135deg, #667eea, #764ba2);
}

.stat-icon.photographers {
  background: linear-gradient(135deg, #f093fb, #f5576c);
}

.stat-icon.orders {
  background: linear-gradient(135deg, #4facfe, #00f2fe);
}

.stat-icon.revenue {
  background: linear-gradient(135deg, #43e97b, #38f9d7);
}

.stat-info h3 {
  margin: 0 0 8px 0;
  color: #606266;
  font-size: 14px;
  font-weight: normal;
}

.stat-number {
  margin: 0;
  color: #303133;
  font-size: 24px;
  font-weight: bold;
}

.announcements {
  max-height: 300px;
  overflow-y: auto;
}

.announcement-item {
  padding: 15px 0;
  border-bottom: 1px solid #f0f0f0;
}

.announcement-item:last-child {
  border-bottom: none;
}

.announcement-item h4 {
  margin: 0 0 8px 0;
  color: #303133;
  font-size: 16px;
}

.announcement-item p {
  margin: 0 0 8px 0;
  color: #606266;
  font-size: 14px;
  line-height: 1.5;
}

.notice-time {
  color: #909399;
  font-size: 12px;
}

/* 用户管理样式 */
.users-management {
  min-height: calc(100vh - 200px);
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.header-actions {
  display: flex;
  align-items: center;
}

.table-footer {
  margin-top: 20px;
  padding-top: 20px;
  border-top: 1px solid #f0f0f0;
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 10px;
}

.el-container {
  flex-direction: row-reverse !important;
}

.dashboard,
.users-management,
.photographers-management {
  width: 100%;
  margin: 0;
  padding: 0;
}

.el-card {
  width: 100%;
  box-sizing: border-box;
  margin: 0 0 20px 0;
}

.admin-nav {
  display: flex;
  gap: 16px;
  background: #f5f7fa;
  padding: 12px 24px;
  border-bottom: 1px solid #eee;
  margin-bottom: 16px;
}

.admin-nav-link {
  color: #409EFF;
  font-weight: bold;
  text-decoration: none;
  padding: 4px 12px;
  border-radius: 4px;
}

.admin-nav-link.router-link-active {
  background: #e6f0fa;
}
</style> 